import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import 'ad_fetcher.dart';
import 'ad_type.dart';

class InterstitialAd extends StatefulWidget {
  final AdType type;
  final VoidCallback onShow;
  final void Function(String error) onError;
  final VoidCallback onClose;
  final String? zoneId;

  const InterstitialAd({
    super.key,
    required this.type,
    required this.onShow,
    required this.onError,
    required this.onClose,
    this.zoneId,
  });

  @override
  State<InterstitialAd> createState() => _InterstitialAdState();
}

class _InterstitialAdState extends State<InterstitialAd> {
  bool isLoading = true; // 是否正在加载广告
  bool isFailed = false; // 是否加载失败
  bool hasLogged = false; // 避免重复触发日志
  Map<String, dynamic>? selectedAd;

  @override
  void initState() {
    super.initState();
    loadAd();
  }

  Future<void> loadAd() async {
    try {
      List<dynamic> ads = await AdFetcher.fetchAds(widget.type, zoneId: widget.zoneId);
      if (ads.isEmpty) throw Exception('No ads available');

      setState(() {
        selectedAd = ads.first;
        isLoading = false;
        isFailed = false;
      });

      WidgetsBinding.instance.addPostFrameCallback((_) {
        widget.onShow(); // **广告成功加载后触发 onShow**
      });
    } catch (e) {
      debugPrint('Failed to fetch ads: $e');

      widget.onError(e.toString()); // **触发 onError 回调**

      if (mounted) {
        Navigator.of(context).pop(); // **广告失败，自动关闭弹窗**
      }
    }
  }

  void _sendLog() async {
    
      // **这里可以加网络请求发送日志**
    if (selectedAd == null) return;
    final logUrl = selectedAd!['logUrl'];
    if (logUrl != null) {
        await AdFetcher.logUrl(logUrl);
    }
    
  }

  @override
  Widget build(BuildContext context) {
    bool isPortrait = MediaQuery.of(context).orientation == Orientation.portrait;

    if (isLoading) {
      return const Center(
        child: CircularProgressIndicator(), // **广告加载中**
      );
    }

    if (selectedAd == null || isFailed) {
      return const SizedBox(); // **加载失败时不显示广告**
    }

    return Stack(
      alignment: Alignment.bottomCenter,
      children: [
        // **半透明黑色背景**
        Positioned.fill(
          child: Container(
            color: Colors.black54,
          ),
        ),
        // **广告图片**
        Container(
          padding: const EdgeInsets.all(20),
          child: AspectRatio(
            aspectRatio: isPortrait ? 9 / 16 : 16 / 9,
            child: GestureDetector(
              onTap: () async {
                if (selectedAd != null) {
                  // 点击广告跳转
                  final clickUrl = selectedAd!['clickUrl'];
                  if (clickUrl != null) {
                    debugPrint("Clicked on banner: $clickUrl");
                    final Uri uri = Uri.parse(clickUrl);
                    await launchUrl(uri);
                  }
                }
              },
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12),
                ),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: Image.network(
                    selectedAd!['bannerContent'], // **广告图片 URL**
                    fit: BoxFit.cover,
                    loadingBuilder: (context, child, loadingProgress) {
                      if (loadingProgress == null) {
                        // **图片加载完成后触发 sendLog**
                        if (!hasLogged) {
                          hasLogged = true;
                          WidgetsBinding.instance.addPostFrameCallback((_) {
                            _sendLog();
                          });
                        }
                        return child;
                      }
                      return const SizedBox.shrink();
                    },
                    errorBuilder: (context, error, stackTrace) {
                      debugPrint("❌ Image load failed: $error");
                      return const SizedBox.shrink(); // **图片加载失败时不占空间**
                    },
                  ),
                ),
              ),
            ),
          ),
        ),
        // **关闭按钮**
        Positioned(
          bottom: 40,
          child: GestureDetector(
            onTap: () {
              widget.onClose(); // **触发广告关闭回调**
              Navigator.of(context).pop(); // **关闭广告弹窗**
            },
            child: Container(
              width: 40,
              height: 40,
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black54,
              ),
              child: const Icon(Icons.close, color: Colors.white, size: 24),
            ),
          ),
        ),
      ],
    );
  }
}

void showInterstitialAd(BuildContext context, AdType type, void Function(String error) onError, void Function() onClose, void Function() onShow ,{String? zoneId}) {
  showDialog(
    context: context,
    barrierDismissible: false, // 不允许点击外部关闭
    builder: (BuildContext context) {
      return Dialog(
        backgroundColor: Colors.transparent, // 透明背景
        insetPadding: EdgeInsets.zero, // 让弹窗填满屏幕
        child: InterstitialAd(
          type: type, // 传入插屏广告类型
          zoneId: zoneId, // 可选的广告区域 ID
          onShow: onShow,
          onError: onError,
          onClose: onClose,
        ),
      );
    },
  );
}
